const express = require("express");
const bcryptjs = require("bcryptjs");
const UserModel = require("../models/users");

const router = express.Router();

/**
 * 用户登录
 */
router.post("/sign-in", async (req, res) => {
  // 1. 获取前端传递过来的 email 与 password
  const { email, password } = req.body;
  // 2. 查询指定 email 的用户
  const user = await UserModel.findOne({ email });
  let isOk = false;
  if (user) {
    // 3. 校验密码是否正确
    isOk = await bcryptjs.compare(password, user.password);
  }

  if (!isOk) {
    res.send({
      code: -1,
      msg: "用户名或密码不正确"
    });
  } else {
    res.send({
      code: 0,
      msg: "登录成功",
      data: {
        userInfo: {
          id: user._id,
          nickname: user.nickname,
          email: user.email
        }
      }
    });
  }
});

/**
 * 用户注册
 */
router.post("/sign-up", async (req, res) => {
  // 1. 获取前端传递过来的参数
  const { email, password, nickname, gender } = req.body;
  // 2. 判断当前用户是否已经被注册过了
  const user = await UserModel.findOne({ email });
  if (user) {
    res.send({
      code: -1,
      msg: "邮箱已经被注册过了！"
    });
    return;
  }
  // 3. 存储到数据库中
  const newUser = new UserModel({
    email,
    password: await bcryptjs.hash(password, 10),
    nickname,
    gender
  });

  await newUser.save();

  res.send({
    code: 0,
    msg: "注册成功"
  });
});

module.exports = router;
